//导入axios  npm install axios
import axios from 'axios';
//js文件中导入router的方法
import router from '@/router'
//导入token
import { useTokenStore } from '@/stores/token.js';
//组件库消息提示
import { ElMessage } from 'element-plus'

//定义一个变量,记录公共的前缀
const baseURL = '/api';
const ignored = [
    { url: '/admin/register', method: 'post' },
    { url: '/admin/login', method: 'post' }
]; //忽略的请求路径和方法

const instance = axios.create({ baseURL })

const isUrlIgnored = (url, method) => {
    return ignored.some(item => url.startsWith(item.url) && item.method === method);
};

//添加响应拦截器
instance.interceptors.response.use(
    result => {
        console.log(result);
        if (result.status === 200) return result.data;
        ElMessage.error(result.data.message ? result.data.message : '服务异常')
        return Promise.resolve(result.data)
    },
    err => {
        let response = err.response;
        if (response) {
            console.log(response)
            if (response.status === 401) {
                ElMessage.error("请先登录")
                router.push('/login')
            } else if (response.status === 403) {
                ElMessage.error("权限不足")
            } else {
                ElMessage.error(response.data.message ?? '响应服务异常')
            }
        } else {
            ElMessage.error('网络错误或服务器未响应')
        }
        console.log(err)
        return Promise.reject(err); // 异步的状态转化成失败的状态
    }
)

//添加请求拦截器
instance.interceptors.request.use(
    config => {
        console.log('正在请求路径：' + config.url);
        if (isUrlIgnored(config.url, config.method)) {
            console.log('该请求路径无需设置请求头');
        } else {
            const tokenStore = useTokenStore();
            if (tokenStore.token){
                config.headers.Authorization = tokenStore.token;
                console.log("token: " + config.headers.Authorization);
            }
            else
                console.log('Token为空, 未设置请求头')
        }
        return config;
    },
    err => {
        ElMessage.error(err.message ?? '请求服务异常')
        console.log(err)
        return Promise.reject(err)
    }
)

export default instance;
